<template>
	<div class="chat-input-area">
		<div v-if="quoteMessage" class="quote-message">
			<div class="quote-header">
				<span>引用 {{ quoteMessage.quoteMessage.sendNickName }} 的消息</span>
				<div class="delete-quote-btn" @click="clearQuoteMessage" title="删除引用">
					<el-icon><close /></el-icon>
				</div>
			</div>
			<div class="quote-content">
				<template v-if="quoteMessage.quoteMessage.type === $enums.MESSAGE_TYPE.TEXT">
					<span>{{ quoteMessage.quoteMessage.content }}</span>
				</template>
				<template v-if="quoteMessage.quoteMessage.type === $enums.MESSAGE_TYPE.IMAGE">
					<span>[图片]</span>
				</template>
				<template v-if="quoteMessage.quoteMessage.type === $enums.MESSAGE_TYPE.FILE">
					<span>[文件]</span>
				</template>
				<template v-if="quoteMessage.quoteMessage.type === $enums.MESSAGE_TYPE.AUDIO">
					<span>[语音]</span>
				</template>
			</div>
		</div>

		<div  class="chat-input-area">
			<div  v-if="!isProhibited" :class="['edit-chat-container',isEmpty?'':'not-empty']" contenteditable="true" @paste.prevent="onPaste"
				@keydown="onKeydown" @compositionstart="compositionFlag=true" @compositionend="onCompositionEnd"
				@input="onEditorInput" @mousedown="onMousedown" ref="content" @blur="onBlur" @focus="onFocus">
			</div>
			<chat-at-box v-if="!isProhibited" @select="onAtSelect" :search-text="atSearchText" ref="atBox" :ownerId="ownerId"
				:members="groupMembers"></chat-at-box>

			<div v-else class="prohibition-tip">
				<el-icon><warning /></el-icon>
				<span>{{ prohibitionTip }}</span>
			</div>
		</div>
	</div>
		
		
</template>

<script>
	import ChatAtBox from "./ChatAtBox.vue";
	import groupPermission from '@/utils/groupPermission';
	import { Close, Warning } from '@element-plus/icons-vue';

	export default {
		name: "ChatInput",
		components: { 
			ChatAtBox,
			Close,
			Warning
		},
		props: {
			ownerId: {
				type: String,
			},
			groupMembers: {
				type: Array,
			},
			prohibition: {
				type: Boolean,
				default: false
			},
			chatType: {
				type: String,
				required: true
			}
		},
		data() {
			return {
				imageList: [],
				fileList: [],
				currentId: 0,
				atSearchText: null,
				compositionFlag: false,
				atIng: false,
				isEmpty: true,
				changeStored: true,
				blurRange: null,
				localProhibition: false,
				tipText: '',
				quoteMessage: null
			}
		},
		computed: {
			isProhibited() {
				return this.localProhibition || this.prohibition;
			},
			prohibitionTip() {
				// const targetId = this.$store.state.chatStore.activeChat.targetId;
				// const activeGroup = this.$store.state.groupStore.groups.find(g => g.id == targetId);
				// console.log("activeGroup",activeGroup)
				// if (!activeGroup) return '';
				// //先判断自己是否被禁言
				// const currentUserId = this.$store.state.userStore.userInfo.id;
				// const currentMember = activeGroup.groupMembers?.find(m => String(m.userId) == String(currentUserId));
				// if (currentMember?.prohibition === 'Y') {
				// 	return '您已被禁言';
				// }
				// if (activeGroup.prohibition === 'Y') {
				// 	return '全体禁言中';
				// }
				// return ''; // 添加默认返回值
				return this.tipText;
			}
		},
		methods: {
			// 粘贴
			onPaste(e) {
				this.isEmpty = false;
				let txt = e.clipboardData.getData('Text')
				let range = window.getSelection().getRangeAt(0)
				if (range.startContainer !== range.endContainer || range.startOffset !== range.endOffset) {
					range.deleteContents();
				}
				// 粘贴图片和文件时，这里没有数据
				if (txt && typeof(txt) == 'string') {
					let textNode = document.createTextNode(txt);
					range.insertNode(textNode)
					range.collapse();
					return;
				}
				let items = (e.clipboardData || window.clipboardData).items
				if (items.length) {
					for (let i = 0; i < items.length; i++) {
						if (items[i].type.indexOf('image') !== -1) {
							let file = items[i].getAsFile();
							let imagePush = {
								fileId: this.generateId(),
								file: file,
								url: URL.createObjectURL(file)
							};
							this.imageList[imagePush.fileId] = (imagePush);
							let line = this.newLine();
							let imageElement = document.createElement('img');
							imageElement.className = 'chat-image no-text';
							imageElement.src = imagePush.url;
							imageElement.dataset.imgId = imagePush.fileId;
							line.appendChild(imageElement);
							let after = document.createTextNode('\u00A0');
							line.appendChild(after);
							this.selectElement(after, 1);		
						} else {
							let asFile = items[i].getAsFile();
							if (!asFile) {
								continue;
							}
							let filePush = { fileId: this.generateId(), file: asFile };
							this.fileList[filePush.fileId] = (filePush)
							let line = this.newLine();
							let fileElement = this.createFile(filePush);
							line.appendChild(fileElement);
							let after = document.createTextNode('\u00A0');
							line.appendChild(after);
							this.selectElement(after, 1);
						}
					}
				}
				range.collapse();
			},
			selectElement(element, endOffset) {
				try {
					if (!element) return;
					
					let selection = window.getSelection();
					if (!selection) return;

					// 插入元素可能不是立即执行的，vue可能会在入元素后再更新dom
					this.$nextTick(() => {
						try {
							let range = document.createRange();
							range.setStart(element, 0);
							range.setEnd(element, endOffset || 0);
							
							if (element.firstChild) {
								range.selectNodeContents(element.firstChild);
							}
							
							range.collapse();
							selection.removeAllRanges();
							selection.addRange(range);
							
							// 需要时自动聚焦
							if (element.focus) {
								element.focus();
							}
						} catch (error) {
							console.warn('Select element failed:', error);
						}
					});
				} catch (error) {
					console.warn('Select element failed:', error);
				}
			},
			// 输入法结束
			onCompositionEnd(e) {
				this.compositionFlag = false;
				this.onEditorInput(e);
			},
			// 按键按下	
			onKeydown(e) {
				if (e.keyCode === 13) {
					e.preventDefault();
					e.stopPropagation();
					if (this.atIng) {
						console.log('选中at的人')
						this.$refs.atBox.select();
						return;
					}
					if (e.ctrlKey) {
						let line = this.newLine();
						let after = document.createTextNode('\u00A0');
						line.appendChild(after);
						this.selectElement(line.childNodes[0], 0);
					} else {
						// 中文输入标记
						if (this.compositionFlag) {
							return;
						}
						this.submit();
					}
					return;
				}
				// 删除键
				if (e.keyCode === 8) {
					// 等待dom更新
					setTimeout(() => {
						let s = this.$refs.content.innerHTML.trim();
						// 空dom时，需要刷新dom
						if (s === '' || s === '<br>' || s === '<div>&nbsp;</div>' ) {
							// 拼接随机长度的空格，以刷新dom
							this.empty();
							this.isEmpty = true;
							this.selectElement(this.$refs.content);
						} else {
							this.isEmpty = false;
						}
					})
				}
				// at框打开时，上下键移动特殊处理
				if (this.atIng) {
					if (e.keyCode === 38) {
						e.preventDefault();
						e.stopPropagation();
						this.$refs.atBox.moveUp();
					}
					if (e.keyCode === 40) {
						e.preventDefault();
						e.stopPropagation();
						this.$refs.atBox.moveDown();
					}
				}

			},
			// 选择at的人
			onAtSelect(member) {
				this.atIng = false;
				// 选中输入的 @xx 符
				let blurRange = this.blurRange;
				let endContainer = blurRange.endContainer
				let startOffset = endContainer.data.indexOf("@"+this.atSearchText);
				let endOffset = startOffset + this.atSearchText.length + 1;
				blurRange.setStart(blurRange.endContainer, startOffset);
				blurRange.setEnd(blurRange.endContainer,  endOffset);
				blurRange.deleteContents()
				blurRange.collapse();
				this.focus();
				// 创建元素节点
				let element = document.createElement('SPAN')
				element.className = "chat-at-user";
				element.dataset.id = member.userId;
				element.contentEditable = 'false'
				element.innerText = `@${member.showNickName}`
				blurRange.insertNode(element)
				// 光标移动到末尾
				blurRange.collapse()

				// 插入空格
				let textNode = document.createTextNode('\u00A0');
				blurRange.insertNode(textNode);

				blurRange.collapse()
				this.atSearchText = "";
				this.selectElement(textNode, 1);
			},
			onEditorInput(e) {
				try {
					this.isEmpty = false;
					this.changeStored = false;
					
					if (this.$props.groupMembers && !this.compositionFlag) {
						let selection = window.getSelection();
						if (!selection || !selection.rangeCount) return;

						let range = selection.getRangeAt(0);
						let endContainer = range.endContainer;
						let endOffset = range.endOffset;
						let textContent = endContainer.textContent || '';
						
						// 找到最近的 @ 符号位置
						let startIndex = textContent.lastIndexOf('@', endOffset);
						
						// 如果找到 @ 符号，并且它在当前光标之前
						if (startIndex !== -1 && startIndex < endOffset) {
							let searchText = textContent.substring(startIndex + 1, endOffset).trim();
							this.atSearchText = searchText;
							
							// 如果是刚输入 @ 符号，显示选择框
							if (searchText === '') {
								this.showAtBox(e);
							} else {
								// 已经有搜索文本，更新 atBox 的位置
								if (this.atIng) {
									let pos = range.getBoundingClientRect();
									this.$refs.atBox.updatePosition({
										x: pos.x,
										y: pos.y
									});
								}
							}
							this.atIng = true;
						} else {
							// 如果没有找到 @ 符号，关闭选择框
							if (this.atIng) {
								this.$refs.atBox.close();
								this.atIng = false;
							}
						}
					}
				} catch (error) {
					console.warn('Editor input failed:', error);
				}
			},
			// 失去焦点
			onBlur(e) {
				this.updateRange();
				
			},
			// 聚焦
			onFocus(e){
				this.$emit('selffocus', e);
			},
			// 鼠标按下
			onMousedown() {
				if (this.atIng) {
					this.$refs.atBox.close();
					this.atIng = false;
				}
			},
			//插入表情
			insertEmoji(emojiText) {
				let emojiElement = document.createElement('img');
				emojiElement.className = 'chat-emoji no-text';
				emojiElement.dataset.emojiCode = emojiText;
				emojiElement.src = this.$emo.textToUrl(emojiText);

				let blurRange = this.blurRange;
				if (!blurRange) {
					this.focus();
					this.updateRange();
					blurRange = this.blurRange;
				}
				if (blurRange.startContainer !== blurRange.endContainer || blurRange.startOffset !== blurRange.endOffset) {
					blurRange.deleteContents();
				}
				blurRange.insertNode(emojiElement);
				blurRange.collapse()

				let textNode = document.createTextNode('\u00A0');
				blurRange.insertNode(textNode)
				blurRange.collapse()

				this.selectElement(textNode);
				this.updateRange();
				this.isEmpty = false;
			},
			generateId() {
				return this.currentId++;
			},
			// 创建文件
			createFile(filePush) {
				let file = filePush.file;
				let fileId = filePush.fileId;
				let container = document.createElement('div');
				container.className = 'chat-file-container no-text';
				container.contentEditable = 'false';
				container.dataset.fileId = fileId;

				let left = document.createElement('div');
				left.className = 'file-position-left';
				container.appendChild(left);

				let icon = document.createElement('div');
				icon.className = 'el-icon-document';
				left.appendChild(icon);

				let right = document.createElement('div');
				right.className = 'file-position-right';
				container.appendChild(right);

				let fileName = document.createElement('div');
				fileName.className = 'file-name';
				fileName.innerText = file.name;

				let fileSize = document.createElement('div');
				fileSize.className = 'file-size';
				fileSize.innerText = this.sizeConvert(file.size);

				right.appendChild(fileName);
				right.appendChild(fileSize);

				return container;
			},
			// 文件大小
			sizeConvert(len) {
				if (len < 1024) {
					return len + 'B';
				} else if (len < 1024 * 1024) {
					return (len / 1024).toFixed(2) + 'KB';
				} else if (len < 1024 * 1024 * 1024) {
					return (len / 1024 / 1024).toFixed(2) + 'MB';
				} else {
					return (len / 1024 / 1024 / 1024).toFixed(2) + 'GB';
				}
			},
			// 更新范围
			updateRange() {
				try {
					let selection = window.getSelection();
					if (selection && selection.rangeCount > 0) {
						this.blurRange = selection.getRangeAt(0);
					}
				} catch (error) {
					console.warn('Update range failed:', error);
					this.blurRange = null;
				}
			},
			// 创建新行
			newLine() {
				try {
					let selection = window.getSelection();
					// 添加判断，确保有选区
					if (!selection || !selection.rangeCount) {
						let divElement = document.createElement('div');
						divElement.innerHTML = '';
						if (this.$refs.content) {
							this.$refs.content.append(divElement);
						}
						return divElement;
					}

					let range = selection.getRangeAt(0);
					let divElement = document.createElement('div');
					let endContainer = range.endContainer;
					let parentElement = endContainer.parentElement;
					
					if (parentElement && this.$refs.content && parentElement.parentElement === this.$refs.content) {
						divElement.innerHTML = endContainer.textContent.substring(range.endOffset).trim(); 
						endContainer.textContent = endContainer.textContent.substring(0, range.endOffset);
						parentElement.insertAdjacentElement('afterend', divElement);
					} else {
						divElement.innerHTML = '';
						if (this.$refs.content) {
							this.$refs.content.append(divElement);
						}
					}
					return divElement;
				} catch (error) {
					console.warn('Create new line failed:', error);
					let divElement = document.createElement('div');
					divElement.innerHTML = '';
					if (this.$refs.content) {
						this.$refs.content.append(divElement);
					}
					return divElement;
				}
			},
			// 清空
			clear() {
				this.empty();
				this.imageList = [];
				this.fileList = [];
				this.clearQuoteMessage();
			},
			// 清空
			empty() {
				if (!this.$refs.content) return;
				
				this.$refs.content.innerHTML = "<div></div>";
				this.isEmpty = true;
				this.$nextTick(() => {
					if (this.$refs.content) {
						this.$refs.content.focus();
					}
				});
			},
			// 显示at弹窗
			showAtBox(e) {
				this.atIng = true;
				// show之后会自动更新当前搜索的text
				// this.atSearchText = "";
				let selection = window.getSelection()
				let range = selection.getRangeAt(0)
				// 光标所在坐标
				let pos = range.getBoundingClientRect();
				this.$refs.atBox.open({
					x: pos.x,
					y: pos.y
				})
				// 记录光标所在位置
				this.updateRange();
			},
			// 转义
			html2Escape(strHtml) {
				return strHtml.replace(/[<>&"]/g, function(c) {
					return {
						'<': '&lt;',
						'>': '&gt;',
						'&': '&amp;',
						'"': '&quot;'
					} [c];
				});
			},
			// 提交
			submit() {
				let nodes = this.$refs.content.childNodes;
				let fullList = [];
				let tempText = '';
				let atUserIds = [];
				let each = (nodes) => {
					for (let i = 0; i < nodes.length; i++) {
						let node = nodes[i];
						if (!node) {
							continue;
						}
						if (node.nodeType === 3) {
							tempText += this.html2Escape(node.textContent);
							continue;
						}
						let nodeName = node.nodeName.toLowerCase();
						if (nodeName === 'script') {
							continue;
						}
						let text = tempText.trim();
						if (nodeName === 'img') {
							let imgId = node.dataset.imgId;
							if (imgId) {
								if (text) {
									fullList.push({
										type: 'text',
										content: text,
										atUserIds: atUserIds,
										quoteId: this.quoteMessage?.quoteMessage?.id
									})
									tempText = '';
									atUserIds = []
								}
								fullList.push({
									type: 'image',
									content: this.imageList[imgId]
								})
							} else {
								let emojiCode = node.dataset.emojiCode;
								tempText += emojiCode;
							}
						} else if (nodeName === 'div') {
							let fileId = node.dataset.fileId
							// 文件
							if (fileId) {
								if (text) {
									fullList.push({
										type: 'text',
										content: text,
										atUserIds: atUserIds,
										quoteId: this.quoteMessage?.quoteMessage?.id
									})
									tempText = '';
									atUserIds = []
								}
								fullList.push({
									type: 'file',
									content: this.fileList[fileId]
								})
							} else {
								tempText += '\n';
								each(node.childNodes);
							}
						} else if (nodeName === 'span') {
							if(node.dataset.id){
								tempText += node.innerHTML;
								atUserIds.push(node.dataset.id)
							}else {
								tempText += node.outerHtml;
							}
						}
					}
				}
				each(nodes)
				let text = tempText.trim();
				if (text !== '') {
					fullList.push({
						type: 'text',
						content: text,
						atUserIds: atUserIds,
						quoteId: this.quoteMessage?.quoteMessage?.id
					})
				}

				this.$emit('submit', fullList);
				this.clearQuoteMessage();
				this.clear();
			},
			// 聚焦
			focus() {
				if (this.$refs.content) {
					this.$refs.content.focus();
				}
			},
			// 清空
			clearInput() {
				if (this.$refs.content) {
					this.$refs.content.innerHTML = '';
				}
			},
			// 禁用
			disableInput() {
				if (this.$refs.content) {
					this.$refs.content.setAttribute('contenteditable', 'false');
				}
			},
			// 启用
			enableInput() {
				if (this.$refs.content) {
					this.$refs.content.setAttribute('contenteditable', 'true');
				}
			},
			// 设置引用消息
			setQuoteMessage(message) {
				this.quoteMessage = message;
				this.focus();
			},
			// 清空引用消息
			clearQuoteMessage() {
				this.quoteMessage = null;
			}
		},
		watch: {
			prohibition: {
				immediate: true,
				handler(newVal) {
					this.localProhibition = newVal;
					if(this.$store.state.chatStore.activeChat.type == 'GROUP'){
						const targetId = this.$store.state.chatStore.activeChat.targetId;
						let params = {
						gid: targetId,
						}
						// 使用 dispatch 调用 action
						this.$store.dispatch('findGroups2', params).then((data) => {
							if (!data) return;
							//先判断自己是否被禁言
							const currentUserId = this.$store.state.userStore.userInfo.id;
							const currentMember = data.groupMembers?.find(m => String(m.userId) == String(currentUserId));
							if (data.prohibition === 'Y') {
								this.tipText = '全体禁言中';
							}
							if (currentMember?.prohibition === 'Y') {
								this.tipText = '您已被禁言';
							}
						});
						// 使用 nextTick 确保状态更新后再执行 DOM 操作
						this.$nextTick(() => {
							if (newVal) {
								this.clearInput();
								this.disableInput();
							} else {
								this.enableInput();
							}
						});
					}
				}
			}
		},
		// 销毁
		beforeDestroy() {
			this.clearInput();
		},
		// 挂载	
		mounted() {
			if (!this.isProhibited && this.$refs.content) {
				this.$refs.content.setAttribute('contenteditable', 'true');
			}
		}
	}
</script>

<style lang="scss">
	.chat-input-area {
		width: 100%;
		height: 100%;
		position: relative;

		.edit-chat-container {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			outline: none;
			padding: 5px;
			line-height: 30px;
			font-size: 16px;
			text-align: left;
			overflow-y: scroll;

			>div {
				min-height: 20px;
			}

			.chat-image {
				display: block;
				max-width: 200px;
				max-height: 100px;
				border: 1px solid #e6e6e6;
				cursor: pointer;
			}

			.chat-emoji {
				width: 30px;
				height: 30px;
				vertical-align: top;
				cursor: pointer;
			}

			.chat-file-container {
				max-width: 65%;
				padding: 10px;
				border: 2px solid #587ff0;
				display: flex;
				background: #eeeC;
				border-radius: 10px;

				.file-position-left {
					display: flex;
					width: 80px;
					justify-content: center;
					align-items: center;

					.el-icon-document {
						font-size: 40px;
						text-align: center;
						color: #d42e07;
					}
				}

				.file-position-right {
					flex: 1;

					.file-name {
						font-size: 16px;
						font-weight: 600;
						color: #66b1ff;
					}

					.file-size {
						font-size: 14px;
						font-weight: 600;
						color: black;
					}
				}
			}

			.chat-at-user {
				color: #00f;
				font-weight: 600;

				border-radius: 3px;
			}
		}

		.edit-chat-container>div:nth-of-type(1):after {
			content: '请输入消息（按Ctrl+Enter键换行）';
			color: gray;
			position: absolute;
			left: 5px;
			top: 5px;
			pointer-events: none;
		}

		.edit-chat-container.not-empty>div:nth-of-type(1):after {
			display: none;
		}

		.prohibition-tip {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 16px;
			color: #999;
			background-color: #f5f7fa;
			-webkit-user-modify: read-only;
			user-select: none;
			cursor: not-allowed;
		}

		.quote-message {
			margin: 8px;
			padding: 8px;
			background: #ececec;
			border-radius: 4px;
			border-left: 3px solid #409EFF;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
			
			.quote-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 4px;
				
				span {
					font-size: 12px;
					color: #606266;
					font-weight: 500;
				}
				
				.delete-quote-btn {
					cursor: pointer;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 20px;
					height: 20px;
					background-color: #f56c6c;
					border-radius: 50%;
					transition: all 0.2s;
					
					i {
						color: white;
						font-size: 12px;
					}
					
					&:hover {
						transform: scale(1.1);
						background-color: #f78989;
					}
				}
			}
			
			.quote-content {
				font-size: 13px;
				color: #303133;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}
</style>